﻿using Abp.Web.Models;
using MyCompanyName.AbpZeroTemplate.Agent;
using MyCompanyName.AbpZeroTemplate.Agent.Dto;
using MyCompanyName.AbpZeroTemplate.Authorization.Users;
using MyCompanyName.AbpZeroTemplate.Card;
using MyCompanyName.AbpZeroTemplate.Card.Dto;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyCompanyName.AbpZeroTemplate.Web.Areas.Mpa.Controllers
{
    public class CardController : Controller
    {

        private readonly ICardService _cardAppService;
        private readonly IUserAppService _userAppService;
        private readonly IAgentService _agentAppService;
        public CardController(ICardService cardAppService, IUserAppService userAppService, IAgentService agentAppService)
        {
            _cardAppService = cardAppService;
            _userAppService = userAppService;
            _agentAppService = agentAppService;
        }
        // GET: Mpa/Card
        public ActionResult Index()
        {
            return View();
        }

        #region 卡片
        public ActionResult CardList()
        {
            return View();
        }

        /// <summary>
        /// 异步获得卡片的DataTable数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        /// 
        [DontWrapResult]
        public ActionResult GetCardDataTable(int offset, int limit)
        {
            //参数
            string Filter1SearchName = Request["Filter1SearchName"];
            string CardName = Filter1SearchName;
            int PageSize = limit;
            int PageNumber = (offset / limit) + 1;
            //获得数据
            var result = _cardAppService.GetCardDtoList(CardName, PageSize, PageNumber);
            //var resultGet = result.Skip(offset).Take(limit).ToList();
            object data = new { total = result.Items.Count, rows = result.Items };
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="AgentId"></param>
        /// <returns></returns>
        public ActionResult CreteOrUpdate(int CardId)
        {
            CardDto card = new CardDto();
            if (CardId != 0)
            {
                card = _cardAppService.GetCardById(CardId);
            }
            return View(card);
        }
        /// <summary>
        /// 提交系统设置创建的表单
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult CardCreateForm(CreateCardInput input)
        {
            bool IsSuccess = true;
            string ErrorMsg = "";

            try
            {
                int result = _cardAppService.CreateCard(input);
            }
            catch (Exception ex)
            {
                IsSuccess = false;
                ErrorMsg = "创建失败" + ex.Message;
            }
            return Json(
                new
                {
                    status = IsSuccess,
                    errormsg = ErrorMsg
                });
        }

        /// <summary>
        /// 提交系统设置创建的表单
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult CardUpdateForm(UpdateCardInput model)
        {
            bool IsSuccess = true;
            string ErrorMsg = "";

            try
            {
                var result = _cardAppService.UpdateCard(model);
                if (result == true)
                {
                    IsSuccess = true;
                    ErrorMsg = "修改成功";
                }
                else
                {
                    IsSuccess = false;
                    ErrorMsg = "修改失败";
                }
            }
            catch (Exception ex)
            {
                IsSuccess = false;
                ErrorMsg = "修改失败" + ex.Message;
            }
            return Json(
                new
                {
                    status = IsSuccess,
                    errormsg = ErrorMsg
                });
        }

        /// <summary>
        /// 根据卡号获得卡号信息
        /// </summary>
        /// <param name="AccountCode"></param>
        /// <returns></returns>
        [DontWrapResult]
        public ActionResult GetMsgByCard(string Card)
        {
            CardDto result = new CardDto();
            result = _cardAppService.GetAgentByCard(Card);
            return Json(result);
        }
        #endregion

        #region 充值
        /// <summary>
        /// 充值中心
        /// </summary>
        /// <returns></returns>
        public ActionResult RechargeCard()
        {
            return View();
        }
        /// <summary>
        /// 充值中心充值
        /// </summary>
        /// <returns></returns>
        public ActionResult RechargeCards(CreateCardRechargeLogInput input)
        {
            bool isValid = false;
            string errormsg = "";
            bool IsSuccess = true;

            //根据卡号获得卡号信息
            //1、卡号存在
            //2、卡号的代理商 当前代理商能够为该卡号充值

            CardDto card = new CardDto();
            if (!string.IsNullOrEmpty(input.UCCID) && input != null)
            {
                card = _cardAppService.GetAgentByCard(input.UCCID);
            }
            AgentDto agent = new AgentDto();
            //获得卡号信息
            if (card != null)
            {
                if (!string.IsNullOrEmpty(card.AgentCode))
                {
                    agent = _agentAppService.GetAgentByAgentCode(card.AgentCode);
                }
                else
                {
                    errormsg = "该卡号没有绑定代理商!";
                    IsSuccess = false;
                }
                //只能对下线代码商转账
                string ParentAgent = "";
                if (agent != null && agent.AgentLevel == 3)
                {
                    AgentDto agent1 = _agentAppService.GetAgentByAgentCode(agent.SecondAgentCode);
                    ParentAgent = agent1.AgentName;
                }
                else if (agent != null && agent.AgentLevel == 2)
                {
                    AgentDto agent2 = _agentAppService.GetAgentByAgentCode(agent.FirstAgentCode);
                    ParentAgent = agent2.AgentName;
                }


                if (agent != null && ParentAgent == User.Identity.Name)
                {
                    isValid = true;
                }
                //else if (User.Identity.Name.Equals(("admin")))
                //{
                //    isValid = true;
                //}
                else
                {
                    errormsg = "只能给下级代理商充值!";
                    IsSuccess = false;
                }
            }
            else
            {
                errormsg = "卡号不存在!";
                IsSuccess = false;
            }

            if (isValid)
            {
                //调用
                if (true)
                {
                    string result = _cardAppService.CreateCardRecharge(input);
                    JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                    string status = jo["status"].ToString();
                    if (status == "False")
                    {
                        IsSuccess = false;
                    }
                    errormsg = jo["errormsg"].ToString();
                }
                else
                {
                    IsSuccess = false;
                    errormsg = "Invoke Interface Error!";
                }
            }
            return Json(
                new
                {
                    status = IsSuccess,
                    errormsg = errormsg
                });
        }

        /// <summary>
        /// 充值记录
        /// </summary>
        /// <returns></returns>
        public ActionResult RechargeLog()
        {
            return View();
        }
        /// <summary>
        /// 异步获得卡片充值的DataTable数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        /// 
        [DontWrapResult]
        public ActionResult GetRechargeCardLogDataTable(int offset, int limit)
        {
            //参数
            string Filter1SearchName = Request["Filter1SearchName"];
            string RechargeCardName = Filter1SearchName;
            int PageSize = limit;
            int PageNumber = (offset / limit) + 1;
            //获得数据
            var result = _cardAppService.GetCardRechargeLogDtoList(RechargeCardName, PageSize, PageNumber);
            //var resultGet = result.Skip(offset).Take(limit).ToList();
            object data = new { total = result.Items.Count, rows = result.Items };
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 批量划卡
        /// <summary>
        /// 批量划卡
        /// </summary>
        /// <returns></returns>
        public ActionResult TransferCard()
        {
            return View();
        }
        /// <summary>
        /// 批量划卡
        /// </summary>
        /// <returns></returns>
        public ActionResult TransferCards(CreateTransferCardLogInput input)
        {
            //检查充值代理商的有效性
            //根据代理商账号获得获得代理商的
            AgentDto agent = new AgentDto();
            if (!string.IsNullOrEmpty(input.AgentCode))
            {
                agent = _agentAppService.GetAgentByAgentCode(input.AgentCode);
            }

            bool isValid = false; string errormsg = ""; bool IsSuccess = true;
            //只能对下线代码商转账
            string ParentAgent = "";
            if (agent != null && agent.AgentLevel == 3)
            {
                AgentDto agent1 = _agentAppService.GetAgentByAgentCode(agent.SecondAgentCode);
                ParentAgent = agent1.AgentName;
            }
            else if (agent != null && agent.AgentLevel == 2)
            {
                AgentDto agent2 = _agentAppService.GetAgentByAgentCode(agent.FirstAgentCode);
                ParentAgent = agent2.AgentName;
            }


            if (agent != null && ParentAgent == User.Identity.Name)
            {
                isValid = true;
            }
            //else if (User.Identity.Name.Equals(("admin")))
            //{
            //    isValid = true;
            //}
            else
            {
                errormsg = "代理商账号不存在!";
                IsSuccess = false;
            }

            //1、根据转账的流量跟新两个经销商的数据
            //2、创建转账记录
            if (isValid)
            {
                string result = _cardAppService.CreateTransferCard(input);
                JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                string status = jo["status"].ToString();
                if (status == "False")
                {
                    IsSuccess = false;
                }
                errormsg = jo["errormsg"].ToString();
            }
            return Json(
                new
                {
                    status = IsSuccess,
                    errormsg = errormsg
                });
        }

        /// <summary>
        /// 划卡记录
        /// </summary>
        /// <returns></returns>
        public ActionResult TransferCardLog()
        {
            return View();
        }
        /// <summary>
        /// 异步获得划卡记录的DataTable数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        /// 
        [DontWrapResult]
        public ActionResult GetTransferCardLogDataTable(int offset, int limit)
        {
            //参数
            string Filter1SearchName = Request["Filter1SearchName"];
            string TransferCardName = Filter1SearchName;
            int PageSize = limit;
            int PageNumber = (offset / limit) + 1;
            //获得数据
            var result = _cardAppService.GetTransferCardLogDtoList(TransferCardName, PageSize, PageNumber);
            //var resultGet = result.Skip(offset).Take(limit).ToList();
            object data = new { total = result.Items.Count, rows = result.Items };
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}